package com.zenithmind.chat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zenithmind.chat.mapper.*;
import com.zenithmind.chat.pojo.dto.AiChatDTO;
import com.zenithmind.chat.pojo.dto.AiChatMessageDTO;
import com.zenithmind.chat.pojo.entity.*;
import com.zenithmind.chat.pojo.query.AiChatPageQuery;
import com.zenithmind.chat.pojo.vo.AiChatVO;
import com.zenithmind.chat.service.AiChatService;
import com.zenithmind.chat.service.AiService;
import com.zenithmind.chat.service.ModelService;
import com.zenithmind.chat.service.factory.AiServiceFactory;
import com.zenithmind.chat.service.AiChatPermissionService;
import com.zenithmind.chat.service.AiChatValidationService;
import com.zenithmind.chat.service.AiChatCacheService;
import com.zenithmind.chat.enums.ModelType;
import com.zenithmind.chat.temp.PageResult;
import com.zenithmind.common.security.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import com.zenithmind.common.annotation.DataCache;
import com.zenithmind.common.annotation.DataCacheEvict;
import com.zenithmind.common.constant.CacheConstants;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * AI对话服务实现类 - 重构后遵循单一职责原则
 * 主要负责对话的核心业务逻辑，其他功能委托给专门的服务类
 */
@Slf4j
@Service
public class AiChatServiceImpl extends ServiceImpl<AiChatMapper, AiChat> implements AiChatService {

    // === 核心依赖 - 遵循依赖倒置原则 ===
    private final AiChatMessageMapper aiChatMessageMapper;
    private final AiServiceFactory aiServiceFactory;
    private final AiChatPermissionService permissionService;
    private final AiChatValidationService validationService;
    private final AiChatCacheService cacheService;

    // === 向后兼容的依赖 ===
    @Autowired
    @Qualifier("openAiService")
    private AiService openAiService;

    @Autowired
    @Qualifier("ollamaService")
    private AiService ollamaService;

    @Autowired
    private AiChatFavoriteMapper favoriteMapper;

    @Autowired
    private AiChatTagMapper tagMapper;

    @Autowired
    private AiChatTagRelMapper tagRelMapper;

    @Autowired
    private AiChatShareMapper shareMapper;

    @Autowired
    private ModelService modelService;

    // === 构造函数注入 - 遵循依赖倒置原则 ===
    @Autowired
    public AiChatServiceImpl(AiChatMessageMapper aiChatMessageMapper,
                            AiServiceFactory aiServiceFactory,
                            AiChatPermissionService permissionService,
                            AiChatValidationService validationService,
                            AiChatCacheService cacheService) {
        this.aiChatMessageMapper = aiChatMessageMapper;
        this.aiServiceFactory = aiServiceFactory;
        this.permissionService = permissionService;
        this.validationService = validationService;
        this.cacheService = cacheService;
    }
    
    // 添加缓存前缀常量
    private static final String CACHE_CHAT_PREFIX = "ai:chat";
    private static final String CACHE_CHAT_HISTORY_PREFIX = "ai:chat:history";
    private static final String CACHE_CHAT_LIST_PREFIX = "ai:chat:list";
    
    @Override
    @Transactional
    @DataCacheEvict(prefix = CACHE_CHAT_LIST_PREFIX, key = "'user_cache'")
    public String createChat(AiChatDTO aiChatDTO) {
        // 转换为实体
        AiChat aiChat = new AiChat();
        BeanUtils.copyProperties(aiChatDTO, aiChat);

        // 设置用户ID和初始值
        String userId = SecurityUtils.getCurrentUserId();
        aiChat.setUserId(userId);
        aiChat.setTotalTokens(0);
        aiChat.setChatCount(0);
        aiChat.setLastChatTime(LocalDateTime.now());
        aiChat.setStatus(1);
        
        // 设置默认值
        if (aiChat.getTemperature() == null) {
            aiChat.setTemperature(0.7f);
        }
        if (aiChat.getMaxTokens() == null) {
            aiChat.setMaxTokens(2000);
        }
        
        // 处理标签
        if (!CollectionUtils.isEmpty(aiChatDTO.getTags())) {
            aiChat.setTags(String.join(",", aiChatDTO.getTags()));
        }
        
        // 处理共享用户
        if (aiChatDTO.getShareType() != null && aiChatDTO.getShareType() == 2 && 
            !CollectionUtils.isEmpty(aiChatDTO.getSharedUserIds())) {
            aiChat.setSharedUserIds(String.join(",", aiChatDTO.getSharedUserIds()));
        } else {
            // 默认私有
            aiChat.setShareType(0);
        }
        
        // 保存对话
        this.save(aiChat);
        
        // 如果有系统提示词，创建系统消息
        if (StringUtils.hasText(aiChat.getSystemPrompt())) {
            AiChatMessage systemMessage = new AiChatMessage();
            systemMessage.setChatId(aiChat.getId());
            systemMessage.setRole("system");
            systemMessage.setContent(aiChat.getSystemPrompt());
            systemMessage.setTokenCount(estimateTokens(aiChat.getSystemPrompt()));
            systemMessage.setStatus(1);
            aiChatMessageMapper.insert(systemMessage);
        }
        
        // 处理标签关联
        saveTagRelations(aiChat.getId(), aiChatDTO.getTags());
        
        // 处理共享用户
        if (aiChatDTO.getShareType() != null && aiChatDTO.getShareType() == 2) {
            saveShareSettings(aiChat.getId(), userId, aiChatDTO.getSharedUserIds());
        }
        
        return aiChat.getId();
    }
    
    @Override
    @Transactional
    @DataCacheEvict(prefix = CACHE_CHAT_HISTORY_PREFIX, key = "#messageDTO.chatId")
    public AiChatMessage sendMessage(AiChatMessageDTO messageDTO) {
        // 获取对话信息
        AiChat aiChat = this.getById(messageDTO.getChatId());
        if (aiChat == null) {
            throw new RuntimeException("对话不存在");
        }
        
        // 校验权限
        checkPermission(aiChat, SecurityUtils.getCurrentUserId());
        
        // 如果前端传递了模型信息，则更新对话的模型信息
        boolean modelInfoChanged = false;
        if (messageDTO.getModelName() != null && !messageDTO.getModelName().isEmpty()) {
            aiChat.setModelName(messageDTO.getModelName());
            modelInfoChanged = true;
        }
        
        if (messageDTO.getModelType() != null) {
            aiChat.setModelType(messageDTO.getModelType());
            modelInfoChanged = true;
        }
        
        // 如果模型信息有变更，先保存对话信息
        if (modelInfoChanged) {
            this.updateById(aiChat);
        }
        
        // 创建用户消息
        AiChatMessage userMessage = new AiChatMessage();
        userMessage.setChatId(messageDTO.getChatId());
        userMessage.setRole("user");
        userMessage.setContent(messageDTO.getContent());
        userMessage.setTokenCount(estimateTokens(messageDTO.getContent()));
        userMessage.setStatus(1);
        aiChatMessageMapper.insert(userMessage);
        
        // 获取历史消息
        LambdaQueryWrapper<AiChatMessage> historyWrapper = new LambdaQueryWrapper<>();
        historyWrapper.eq(AiChatMessage::getChatId, messageDTO.getChatId())
                    .eq(AiChatMessage::getStatus, 1)
                    .orderByAsc(AiChatMessage::getCreateTime);
        List<AiChatMessage> historyMessages = aiChatMessageMapper.selectList(historyWrapper);
        
        // 根据模型类型调用不同的AI服务
        AiChatMessage aiMessage;
        
        try {
            if (aiChat.getModelType() == 2) { // Ollama
                aiMessage = ollamaService.chat(aiChat, historyMessages, messageDTO.getContent());
            } else { // 默认使用OpenAI
                aiMessage = openAiService.chat(aiChat, historyMessages, messageDTO.getContent());
            }
            
            // 设置父消息ID和状态
        aiMessage.setParentId(userMessage.getId());
        aiMessage.setStatus(1);
            
            // 保存AI回复消息
        aiChatMessageMapper.insert(aiMessage);
        
        // 更新对话信息
        aiChat.setLastChatTime(LocalDateTime.now());
        aiChat.setChatCount(aiChat.getChatCount() + 1);
        aiChat.setTotalTokens(aiChat.getTotalTokens() + userMessage.getTokenCount() + aiMessage.getTokenCount());
        this.updateById(aiChat);
        
        return aiMessage;
        } catch (Exception e) {
            log.error("调用AI服务失败：", e);
            
            // 创建一个错误响应消息
            AiChatMessage errorMessage = new AiChatMessage();
            errorMessage.setChatId(messageDTO.getChatId());
            errorMessage.setRole("assistant");
            errorMessage.setContent("抱歉，AI服务暂时不可用，请稍后再试。");
            errorMessage.setTokenCount(estimateTokens(errorMessage.getContent()));
            errorMessage.setParentId(userMessage.getId());
            errorMessage.setStatus(1);
            aiChatMessageMapper.insert(errorMessage);
            
            // 更新对话信息
            aiChat.setLastChatTime(LocalDateTime.now());
            aiChat.setChatCount(aiChat.getChatCount() + 1);
            aiChat.setTotalTokens(aiChat.getTotalTokens() + userMessage.getTokenCount() + errorMessage.getTokenCount());
            this.updateById(aiChat);
            
            return errorMessage;
        }
    }
    
    @Override
    @DataCache(prefix = CACHE_CHAT_HISTORY_PREFIX, key = "#chatId", expireTime = CacheConstants.TTL_SECONDS_DEFAULT)
    public List<AiChatMessage> getChatHistory(String chatId) {
        // 获取对话信息
        AiChat aiChat = this.getById(chatId);
        if (aiChat == null) {
            log.warn("尝试获取不存在的AI对话历史: {}", chatId);
            return new ArrayList<>(); // 返回空列表而不是抛出异常
        }
        
        // 校验权限
        try {
            checkPermission(aiChat, SecurityUtils.getCurrentUserId());
        } catch (Exception e) {
            log.warn("获取AI对话历史权限验证失败: {}, 错误: {}", chatId, e.getMessage());
            return new ArrayList<>(); // 权限验证失败时也返回空列表
        }
        
        // 获取消息历史
        LambdaQueryWrapper<AiChatMessage> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AiChatMessage::getChatId, chatId)
               .eq(AiChatMessage::getStatus, 1)
               .orderByAsc(AiChatMessage::getCreateTime);
        
        return aiChatMessageMapper.selectList(wrapper);
    }
    
    @Override
    @DataCache(prefix = CACHE_CHAT_PREFIX, key = "#chatId", expireTime = CacheConstants.TTL_SECONDS_DEFAULT)
    public AiChatVO getChatDetail(String chatId) {
        // 获取对话信息
        AiChat aiChat = this.getById(chatId);
        if (aiChat == null) {
            log.warn("尝试获取不存在的AI对话详情: {}", chatId);
            return null; // 返回null而不是抛出异常
        }
        
        // 校验权限
        try {
            checkPermission(aiChat, SecurityUtils.getCurrentUserId());
        } catch (Exception e) {
            log.warn("获取AI对话详情权限验证失败: {}, 错误: {}", chatId, e.getMessage());
            return null; // 权限验证失败时也返回null
        }
        
        // 转换为VO
        AiChatVO vo = new AiChatVO();
        BeanUtils.copyProperties(aiChat, vo);
        
        // 处理标签
        if (StringUtils.hasText(aiChat.getTags())) {
            vo.setTags(Arrays.asList(aiChat.getTags().split(",")));
        }
        
        // 处理共享用户
        if (aiChat.getShareType() != null && aiChat.getShareType() == 2 &&
            StringUtils.hasText(aiChat.getSharedUserIds())) {
            vo.setSharedUserIds(Arrays.asList(aiChat.getSharedUserIds().split(",")));
        }
        
        return vo;
    }
    
    @Override
    @Transactional
    @DataCacheEvict(prefix = CACHE_CHAT_PREFIX, key = "#chatId")
    public boolean deleteChat(String chatId) {
        // 获取对话信息
        AiChat aiChat = this.getById(chatId);
        if (aiChat == null) {
            log.warn("尝试删除不存在的AI对话: {}", chatId);
            return false;
        }

        // 检查权限
        String currentUserId = SecurityUtils.getCurrentUserId();
        checkPermission(aiChat, currentUserId);

        // 删除对话
        boolean success = this.removeById(chatId);

        // 删除对话消息
        if (success) {
            LambdaQueryWrapper<AiChatMessage> messageWrapper = new LambdaQueryWrapper<>();
            messageWrapper.eq(AiChatMessage::getChatId, chatId);
            aiChatMessageMapper.delete(messageWrapper);
            
            // 删除对话标签关联
            LambdaQueryWrapper<AiChatTagRel> tagRelWrapper = new LambdaQueryWrapper<>();
            tagRelWrapper.eq(AiChatTagRel::getChatId, chatId);
            tagRelMapper.delete(tagRelWrapper);
            
            // 删除对话分享设置
            LambdaQueryWrapper<AiChatShare> shareWrapper = new LambdaQueryWrapper<>();
            shareWrapper.eq(AiChatShare::getChatId, chatId);
            shareMapper.delete(shareWrapper);
            
            // 删除对话收藏
            LambdaQueryWrapper<AiChatFavorite> favoriteWrapper = new LambdaQueryWrapper<>();
            favoriteWrapper.eq(AiChatFavorite::getChatId, chatId);
            favoriteMapper.delete(favoriteWrapper);
            
            log.info("成功删除AI对话及相关数据: {}", chatId);
        }
        
        return success;
    }
    
    @Override
    @Transactional
    @DataCacheEvict(prefix = CACHE_CHAT_HISTORY_PREFIX, key = "#chatId")
    public boolean clearChatHistory(String chatId) {
        // 获取对话信息
        AiChat aiChat = this.getById(chatId);
        if (aiChat == null) {
            return false;
        }
        
        // 校验权限
        checkPermission(aiChat, SecurityUtils.getCurrentUserId());
        
        // 保留系统消息
        LambdaQueryWrapper<AiChatMessage> sysMessageQuery = new LambdaQueryWrapper<>();
        sysMessageQuery.eq(AiChatMessage::getChatId, chatId)
                      .eq(AiChatMessage::getRole, "system");
        List<AiChatMessage> sysMessages = aiChatMessageMapper.selectList(sysMessageQuery);
        
        // 删除所有消息
        LambdaQueryWrapper<AiChatMessage> deleteWrapper = new LambdaQueryWrapper<>();
        deleteWrapper.eq(AiChatMessage::getChatId, chatId);
        aiChatMessageMapper.delete(deleteWrapper);
        
        // 重新插入系统消息
        for (AiChatMessage sysMessage : sysMessages) {
            sysMessage.setId(null); // 清除ID以便重新生成
            aiChatMessageMapper.insert(sysMessage);
        }
        
        // 更新对话信息
        aiChat.setTotalTokens(0);
        aiChat.setChatCount(0);
        this.updateById(aiChat);
        
        return true;
    }
    
    @Override
    @DataCacheEvict(prefix = CACHE_CHAT_PREFIX, key = "#chatId")
    public boolean updateChatTitle(String chatId, String title) {
        // 获取对话信息
        AiChat aiChat = this.getById(chatId);
        if (aiChat == null) {
            return false;
        }
        
        // 校验权限
        checkPermission(aiChat, SecurityUtils.getCurrentUserId());
        
        // 更新标题
        aiChat.setTitle(title);
        return this.updateById(aiChat);
    }
    
    @Override
    @DataCacheEvict(prefix = CACHE_CHAT_PREFIX, key = "#chatId")
    public boolean updateSystemPrompt(String chatId, String systemPrompt) {
        // 获取对话信息
        AiChat aiChat = this.getById(chatId);
        if (aiChat == null) {
            return false;
        }
        
        // 校验权限
        checkPermission(aiChat, SecurityUtils.getCurrentUserId());
        
        // 更新系统提示词
        aiChat.setSystemPrompt(systemPrompt);
        
        // 查找现有系统消息
        LambdaQueryWrapper<AiChatMessage> sysMessageQuery = new LambdaQueryWrapper<>();
        sysMessageQuery.eq(AiChatMessage::getChatId, chatId)
                      .eq(AiChatMessage::getRole, "system");
        List<AiChatMessage> sysMessages = aiChatMessageMapper.selectList(sysMessageQuery);
        
        // 删除现有系统消息
        if (!sysMessages.isEmpty()) {
            LambdaQueryWrapper<AiChatMessage> deleteWrapper = new LambdaQueryWrapper<>();
            deleteWrapper.eq(AiChatMessage::getChatId, chatId)
                        .eq(AiChatMessage::getRole, "system");
            aiChatMessageMapper.delete(deleteWrapper);
        }
        
        // 创建新系统消息
        if (StringUtils.hasText(systemPrompt)) {
            AiChatMessage systemMessage = new AiChatMessage();
            systemMessage.setChatId(chatId);
            systemMessage.setRole("system");
            systemMessage.setContent(systemPrompt);
            systemMessage.setTokenCount(estimateTokens(systemPrompt));
            systemMessage.setStatus(1);
            aiChatMessageMapper.insert(systemMessage);
        }
        
        return this.updateById(aiChat);
    }
    
    @Override
    @DataCache(prefix = CACHE_CHAT_LIST_PREFIX, key = "#userId + ':page' + #page.current", expireTime = CacheConstants.TTL_SECONDS_DEFAULT)
    public Page<AiChatVO> getChatPage(Page<AiChat> page, String userId) {
        // 如果没有传入用户ID，使用当前用户ID
        final String finalUserId = !StringUtils.hasText(userId) ? SecurityUtils.getCurrentUserId() : userId;
        
        // 构建查询条件：用户创建的 + 共享给用户的
        LambdaQueryWrapper<AiChat> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AiChat::getUserId, finalUserId)
              .or(w -> w.eq(AiChat::getShareType, 1)  // 公开的
                    .or(w2 -> w2.eq(AiChat::getShareType, 2) // 指定共享且包含当前用户
                                .like(AiChat::getSharedUserIds, finalUserId)))
              .orderByDesc(AiChat::getIsTop, AiChat::getLastChatTime);
              
        // 查询分页数据
        Page<AiChat> resultPage = this.page(page, wrapper);
        
        // 转换为VO
        Page<AiChatVO> voPage = new Page<>(resultPage.getCurrent(), resultPage.getSize(), resultPage.getTotal());
        List<AiChatVO> voList = resultPage.getRecords().stream().map(chat -> {
            AiChatVO vo = new AiChatVO();
            BeanUtils.copyProperties(chat, vo);
            
            // 处理标签
            if (StringUtils.hasText(chat.getTags())) {
                vo.setTags(Arrays.asList(chat.getTags().split(",")));
            }
            
            // 处理共享用户
            if (chat.getShareType() != null && chat.getShareType() == 2 &&
                StringUtils.hasText(chat.getSharedUserIds())) {
                vo.setSharedUserIds(Arrays.asList(chat.getSharedUserIds().split(",")));
            }
            
            return vo;
        }).collect(Collectors.toList());
        
        voPage.setRecords(voList);
        return voPage;
    }
    
    @Override
    @DataCache(prefix = CACHE_CHAT_LIST_PREFIX, key = "#query.userId + ':pageResult' + #query.current", expireTime = CacheConstants.TTL_SECONDS_DEFAULT)
    public PageResult<AiChatVO> getChatPage(AiChatPageQuery query) {
        Page<AiChat> page = query.toPage();
        String userId = StringUtils.hasText(query.getUserId()) ? query.getUserId() : SecurityUtils.getCurrentUserId();
        
        // 构建查询条件
        LambdaQueryWrapper<AiChat> wrapper = new LambdaQueryWrapper<>();
        
        // 基本条件：当前用户的对话 或 共享给用户的对话
        wrapper.eq(AiChat::getUserId, userId)
              .or(w -> w.eq(AiChat::getShareType, 1)  // 公开的
                    .or(w2 -> w2.eq(AiChat::getShareType, 2) // 指定共享且包含当前用户
                                .like(AiChat::getSharedUserIds, userId)));
        
        // 添加查询条件
        wrapper.like(StringUtils.hasText(query.getTitle()), AiChat::getTitle, query.getTitle())
               .eq(StringUtils.hasText(query.getModelId()), AiChat::getModelName, query.getModelId())
               .eq(query.getModelType() != null, AiChat::getModelType, query.getModelType());
        
        // 处理时间范围查询
        if (StringUtils.hasText(query.getBeginTime()) && StringUtils.hasText(query.getEndTime())) {
            wrapper.between(AiChat::getCreateTime, query.getBeginTime(), query.getEndTime());
        } else if (StringUtils.hasText(query.getBeginTime())) {
            wrapper.ge(AiChat::getCreateTime, query.getBeginTime());
        } else if (StringUtils.hasText(query.getEndTime())) {
            wrapper.le(AiChat::getCreateTime, query.getEndTime());
        }
        
        // 设置排序
        wrapper.orderByDesc(AiChat::getIsTop, AiChat::getLastChatTime);
        
        // 查询分页数据
        Page<AiChat> resultPage = this.page(page, wrapper);
        
        // 转换为VO
        List<AiChatVO> voList = resultPage.getRecords().stream().map(chat -> {
            AiChatVO vo = new AiChatVO();
            BeanUtils.copyProperties(chat, vo);
            
            // 处理标签
            if (StringUtils.hasText(chat.getTags())) {
                vo.setTags(Arrays.asList(chat.getTags().split(",")));
            }
            
            // 处理共享用户
            if (chat.getShareType() != null && chat.getShareType() == 2 &&
                StringUtils.hasText(chat.getSharedUserIds())) {
                vo.setSharedUserIds(Arrays.asList(chat.getSharedUserIds().split(",")));
            }
            
            return vo;
        }).collect(Collectors.toList());
        
        // 创建并返回分页结果
        PageResult<AiChatVO> pageResult = new PageResult<>();
        pageResult.setRecords(voList);
        pageResult.setTotal(resultPage.getTotal());
        pageResult.setCurrent(resultPage.getCurrent());
        pageResult.setSize(resultPage.getSize());
        return pageResult;
    }
    
    @Override
    public boolean toggleFavorite(String chatId, Integer isFavorite) {
        // 获取对话信息
        AiChat aiChat = this.getById(chatId);
        if (aiChat == null) {
            return false;
        }
        
        // 校验权限
        checkPermission(aiChat, SecurityUtils.getCurrentUserId());
        
        // 更新收藏状态
        aiChat.setIsFavorite(isFavorite);
        
        // 处理收藏表
        String userId = SecurityUtils.getCurrentUserId();
        if (isFavorite != null && isFavorite == 1) {
            // 添加收藏
            LambdaQueryWrapper<AiChatFavorite> existsWrapper = new LambdaQueryWrapper<>();
            existsWrapper.eq(AiChatFavorite::getUserId, userId)
                       .eq(AiChatFavorite::getChatId, chatId);
            if (favoriteMapper.selectCount(existsWrapper) == 0) {
                AiChatFavorite favorite = new AiChatFavorite();
                favorite.setUserId(userId);
                favorite.setChatId(chatId);
                favoriteMapper.insert(favorite);
            }
        } else {
            // 取消收藏
            LambdaQueryWrapper<AiChatFavorite> deleteWrapper = new LambdaQueryWrapper<>();
            deleteWrapper.eq(AiChatFavorite::getUserId, userId)
                       .eq(AiChatFavorite::getChatId, chatId);
            favoriteMapper.delete(deleteWrapper);
        }
        
        return this.updateById(aiChat);
    }
    
    @Override
    public boolean toggleTop(String chatId, Integer isTop) {
        // 获取对话信息
        AiChat aiChat = this.getById(chatId);
        if (aiChat == null) {
            return false;
        }
        
        // 校验权限
        checkPermission(aiChat, SecurityUtils.getCurrentUserId());
        
        // 更新置顶状态
        aiChat.setIsTop(isTop);
        if (isTop != null && isTop == 1) {
            aiChat.setTopTime(LocalDateTime.now());
        } else {
            aiChat.setTopTime(null);
        }
        
        return this.updateById(aiChat);
    }
    
    @Override
    @Transactional
    @DataCacheEvict(prefix = CACHE_CHAT_PREFIX, key = "#chatId")
    public boolean updateChatTags(String chatId, List<String> tags) {
        // 获取对话信息
        AiChat aiChat = this.getById(chatId);
        if (aiChat == null) {
            return false;
        }
        
        // 校验权限
        checkPermission(aiChat, SecurityUtils.getCurrentUserId());
        
        // 更新标签字段
        aiChat.setTags(CollectionUtils.isEmpty(tags) ? null : String.join(",", tags));
        
        // 保存标签关联
        saveTagRelations(chatId, tags);
        
        return this.updateById(aiChat);
    }
    
    @Override
    @Transactional
    @DataCacheEvict(prefix = CACHE_CHAT_PREFIX, key = "#chatId")
    public boolean updateShareSettings(String chatId, Integer shareType, List<String> sharedUserIds) {
        // 获取对话信息
        AiChat aiChat = this.getById(chatId);
        if (aiChat == null) {
            return false;
        }
        
        // 校验权限（只有创建者可以更改共享设置）
        String currentUserId = SecurityUtils.getCurrentUserId();
        if (!aiChat.getUserId().equals(currentUserId)) {
            throw new RuntimeException("无权限操作");
        }
        
        // 更新共享设置
        aiChat.setShareType(shareType);
        if (shareType != null && shareType == 2 && !CollectionUtils.isEmpty(sharedUserIds)) {
            aiChat.setSharedUserIds(String.join(",", sharedUserIds));
        } else {
            aiChat.setSharedUserIds(null);
        }
        
        // 删除旧的共享记录
        LambdaQueryWrapper<AiChatShare> deleteWrapper = new LambdaQueryWrapper<>();
        deleteWrapper.eq(AiChatShare::getChatId, chatId);
        shareMapper.delete(deleteWrapper);
        
        // 添加新的共享记录
        if (shareType != null && shareType == 2 && !CollectionUtils.isEmpty(sharedUserIds)) {
            saveShareSettings(chatId, currentUserId, sharedUserIds);
        }
        
        return this.updateById(aiChat);
    }
    
    /**
     * 校验操作权限
     */
    private void checkPermission(AiChat aiChat, String currentUserId) {
        // 创建者有权限
        if (currentUserId == null) { // Add null check for safety
             log.warn("currentUserId is null in checkPermission for chat {}. Denying permission.", aiChat.getId());
             throw new RuntimeException("用户未登录或会话已失效");
        }

        if (aiChat.getUserId().equals(currentUserId)) {
            return;
        }
        
        // 公开对话任何人都有权限
        if (aiChat.getShareType() != null && aiChat.getShareType() == 1) {
            return;
        }
        
        // 检查是否有共享权限
        if (aiChat.getShareType() != null && aiChat.getShareType() == 2 && 
            StringUtils.hasText(aiChat.getSharedUserIds())) {
            String[] sharedUserIds = aiChat.getSharedUserIds().split(",");
            for (String userId : sharedUserIds) {
                if (userId.equals(currentUserId)) {
                    return;
                }
            }
        }
        
        throw new RuntimeException("无权限操作");
    }
    
    /**
     * 保存标签关系
     */
    private void saveTagRelations(String chatId, List<String> tagNames) {
        if (CollectionUtils.isEmpty(tagNames)) {
            return;
        }
        
        String userId = SecurityUtils.getCurrentUserId();
        
        // 删除旧的关联关系
        LambdaQueryWrapper<AiChatTagRel> deleteWrapper = new LambdaQueryWrapper<>();
        deleteWrapper.eq(AiChatTagRel::getChatId, chatId);
        tagRelMapper.delete(deleteWrapper);
        
        // 获取或创建标签
        for (String tagName : tagNames) {
            // 查找现有标签
            LambdaQueryWrapper<AiChatTag> tagQuery = new LambdaQueryWrapper<>();
            tagQuery.eq(AiChatTag::getName, tagName)
                   .eq(AiChatTag::getUserId, userId);
            AiChatTag tag = tagMapper.selectOne(tagQuery);
            
            // 如果标签不存在，创建新标签
            if (tag == null) {
                tag = new AiChatTag();
                tag.setName(tagName);
                tag.setColor("#" + generateRandomColor());
                tag.setUserId(userId);
                tag.setUsageCount(1);
                tagMapper.insert(tag);
            } else {
                // 更新使用次数
                tag.setUsageCount(tag.getUsageCount() + 1);
                tagMapper.updateById(tag);
            }
            
            // 创建关联关系
            AiChatTagRel tagRel = new AiChatTagRel();
            tagRel.setChatId(chatId);
            tagRel.setTagId(tag.getId());
            tagRelMapper.insert(tagRel);
        }
    }
    
    /**
     * 保存共享设置
     */
    private void saveShareSettings(String chatId, String ownerId, List<String> sharedUserIds) {
        if (CollectionUtils.isEmpty(sharedUserIds)) {
            return;
        }
        
        for (String userId : sharedUserIds) {
            AiChatShare share = new AiChatShare();
            share.setChatId(chatId);
            share.setOwnerId(ownerId);
            share.setSharedUserId(userId);
            share.setPermission(1); // 默认只读权限
            shareMapper.insert(share);
        }
    }
    
    /**
     * 简单估计token数量（实际项目中应使用更准确的计算方法）
     */
    private Integer estimateTokens(String text) {
        if (!StringUtils.hasText(text)) {
            return 0;
        }
        // 简单估计：中文每字1.5个token，英文每4个字符1个token
        int chineseCount = 0;
        int englishCount = 0;
        for (char c : text.toCharArray()) {
            if (Character.UnicodeBlock.of(c) == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS) {
                chineseCount++;
            } else {
                englishCount++;
            }
        }
        return (int) (chineseCount * 1.5 + englishCount / 4.0);
    }
    
    /**
     * 生成随机颜色
     */
    private String generateRandomColor() {
        Random random = new Random();
        return String.format("%06x", random.nextInt(0xFFFFFF + 1));
    }

    @Override
    @Transactional
    @DataCacheEvict(prefix = CACHE_CHAT_LIST_PREFIX, key = "'user_cache'")
    public String saveOrUpdateChat(AiChatDTO aiChatDTO) {
        // 如果是新建
        if (StringUtils.isEmpty(aiChatDTO.getId())) {
            return createChat(aiChatDTO);
        }
        
        // 获取对话信息
        AiChat aiChat = this.getById(aiChatDTO.getId());
        if (aiChat == null) {
            throw new RuntimeException("对话不存在");
        }
        
        // 校验权限
        checkPermission(aiChat, SecurityUtils.getCurrentUserId());
        
        // 更新对话信息
        BeanUtils.copyProperties(aiChatDTO, aiChat);
        aiChat.setLastChatTime(LocalDateTime.now());
        
        // 处理标签
        if (aiChatDTO.getTags() != null) {
            saveTagRelations(aiChat.getId(), aiChatDTO.getTags());
        }
        
        // 处理共享设置
        if (aiChatDTO.getShareType() != null && aiChatDTO.getShareType() == 2) {
            saveShareSettings(aiChat.getId(), SecurityUtils.getCurrentUserId(), aiChatDTO.getSharedUserIds());
        } else if (aiChatDTO.getShareType() != null && aiChatDTO.getShareType() != 2) {
            // If share type is not 2 (e.g., private or public), clear existing specific shares
            LambdaQueryWrapper<AiChatShare> deleteWrapper = new LambdaQueryWrapper<>();
            deleteWrapper.eq(AiChatShare::getChatId, aiChat.getId());
            shareMapper.delete(deleteWrapper);
            aiChat.setSharedUserIds(null);
            this.updateById(aiChat); // Persist clearing of sharedUserIds
        }

        return aiChat.getId();
    }

    @Override
    public AiChatMessage chatStream(AiChat chat, List<AiChatMessage> messages, String content, org.springframework.web.servlet.mvc.method.annotation.SseEmitter emitter) {
        if (chat == null) {
            // Or throw an IllegalArgumentException, or handle as per specific requirements
            log.error("AiChat object cannot be null in chatStream");
            try {
                emitter.send(org.springframework.web.servlet.mvc.method.annotation.SseEmitter.event().name("error").data("Chat session not found."));
                emitter.complete();
            } catch (java.io.IOException e) {
                log.error("Failed to send error to emitter", e);
            }
            AiChatMessage errorResult = new AiChatMessage();
            errorResult.setContent("Error: Chat session is null.");
            // Populate other fields as necessary for an error message
            return errorResult;
        }

        // 使用工厂模式获取AI服务，遵循开闭原则和依赖倒置原则
        try {
            ModelType modelType = ModelType.fromCode(chat.getModelType());
            AiService aiService = aiServiceFactory.getAiService(modelType);
            return aiService.chatStream(chat, messages, content, emitter);
        } catch (Exception e) {
            log.error("获取AI服务失败，回退到原有逻辑", e);
            // 回退到原有逻辑以保证向后兼容性
            if (chat.getModelType() == 2) { // Ollama
                return ollamaService.chatStream(chat, messages, content, emitter);
            } else { // Default to OpenAI or other model types
                return openAiService.chatStream(chat, messages, content, emitter);
            }
        }
    }

    /**
     * 发送消息并流式返回响应
     * @param messageDTO 消息内容
     * @param emitter SseEmitter 用于发送数据
     * @param userId 当前用户ID
     */
    @Transactional // 注意：流式处理中的事务管理可能需要更细致的考量
    @DataCacheEvict(prefix = CACHE_CHAT_HISTORY_PREFIX, key = "#messageDTO.chatId")
    public void sendMessageStream(AiChatMessageDTO messageDTO, SseEmitter emitter, String userId) {
        AiChat aiChat = this.getById(messageDTO.getChatId());
        if (aiChat == null) {
            try {
                emitter.send(SseEmitter.event().name("error").data("对话不存在"));
                emitter.complete();
            } catch (java.io.IOException e) {
                log.error("发送SSE错误失败", e);
            }
            return;
        }

        checkPermission(aiChat, userId); // 权限校验，使用传入的userId

        boolean modelInfoChanged = false;
        if (messageDTO.getModelName() != null && !messageDTO.getModelName().isEmpty()) {
            aiChat.setModelName(messageDTO.getModelName());
            modelInfoChanged = true;
        }
        if (messageDTO.getModelType() != null) {
            aiChat.setModelType(messageDTO.getModelType());
            modelInfoChanged = true;
        }
        if (modelInfoChanged) {
            this.updateById(aiChat);
        }

        AiChatMessage userMessage = new AiChatMessage();
        userMessage.setChatId(messageDTO.getChatId());
        userMessage.setRole("user");
        userMessage.setContent(messageDTO.getContent());
        userMessage.setTokenCount(estimateTokens(messageDTO.getContent()));
        userMessage.setStatus(1);
        aiChatMessageMapper.insert(userMessage); // 保存用户消息

        LambdaQueryWrapper<AiChatMessage> historyWrapper = new LambdaQueryWrapper<>();
        historyWrapper.eq(AiChatMessage::getChatId, messageDTO.getChatId())
                      .eq(AiChatMessage::getStatus, 1)
                      .orderByAsc(AiChatMessage::getCreateTime);
        List<AiChatMessage> historyMessages = aiChatMessageMapper.selectList(historyWrapper);

        AiChatMessage finalAiMessageFromStream;
        try {
            if (aiChat.getModelType() == 2) { // Ollama
                finalAiMessageFromStream = ollamaService.chatStream(aiChat, historyMessages, messageDTO.getContent(), emitter);
            } else { // OpenAI
                finalAiMessageFromStream = openAiService.chatStream(aiChat, historyMessages, messageDTO.getContent(), emitter);
            }

            // 只有当流式调用成功返回（没有在 chatStream 内部 completeWithError）时，才保存消息
            if (finalAiMessageFromStream != null && finalAiMessageFromStream.getContent() != null && 
                !finalAiMessageFromStream.getContent().startsWith("AI服务流式处理失败") &&
                !finalAiMessageFromStream.getContent().startsWith("OpenAI流式处理失败")) {
                
                finalAiMessageFromStream.setParentId(userMessage.getId()); // 设置父消息ID
                finalAiMessageFromStream.setStatus(1);
                aiChatMessageMapper.insert(finalAiMessageFromStream); // 保存完整的AI消息

                // 更新对话统计信息
                aiChat.setLastChatTime(LocalDateTime.now());
                aiChat.setChatCount(aiChat.getChatCount() + 1);
                aiChat.setTotalTokens(aiChat.getTotalTokens() + userMessage.getTokenCount() + finalAiMessageFromStream.getTokenCount());
                this.updateById(aiChat);
            }

        } catch (Exception e) {
            log.error("调用AI流式服务失败或处理后续逻辑失败：", e);
            try {
                emitter.send(SseEmitter.event().name("error").data("AI service error: " + e.getMessage()));
                emitter.completeWithError(e);
            } catch (java.io.IOException ex) {
                log.error("发送SSE错误失败", ex);
            }
        }
    }

    // =================== 管理平台接口实现 ===================
    
    @Override
    @DataCache(prefix = CACHE_CHAT_LIST_PREFIX, key = "#query.userId + ':pageResult' + #query.current", expireTime = CacheConstants.TTL_SECONDS_DEFAULT)
    public PageResult<AiChatVO> getAllChatPage(AiChatPageQuery query) {
        // 创建分页对象
        Page<AiChat> page = query.toPage();
        
        // 构建查询条件
        LambdaQueryWrapper<AiChat> wrapper = new LambdaQueryWrapper<>();
        
        // 管理平台查询所有用户的对话，不需要增加用户ID的限制
        // 但可以增加其他过滤条件
        wrapper.like(StringUtils.hasText(query.getTitle()), AiChat::getTitle, query.getTitle())
               .eq(StringUtils.hasText(query.getModelId()), AiChat::getModelName, query.getModelId())
               .eq(query.getModelType() != null, AiChat::getModelType, query.getModelType())
               .eq(query.getStatus() != null, AiChat::getStatus, query.getStatus()); // 增加对状态的筛选
        
        // 如果指定了用户ID，则按用户ID过滤
        if (StringUtils.hasText(query.getUserId())) {
            wrapper.eq(AiChat::getUserId, query.getUserId());
        }
        
        // 处理时间范围查询
        if (StringUtils.hasText(query.getBeginTime()) && StringUtils.hasText(query.getEndTime())) {
            wrapper.between(AiChat::getCreateTime, query.getBeginTime(), query.getEndTime());
        } else if (StringUtils.hasText(query.getBeginTime())) {
            wrapper.ge(AiChat::getCreateTime, query.getBeginTime());
        } else if (StringUtils.hasText(query.getEndTime())) {
            wrapper.le(AiChat::getCreateTime, query.getEndTime());
        }
        
        // 设置排序
        wrapper.orderByDesc(AiChat::getCreateTime);
        
        // 查询分页数据
        Page<AiChat> resultPage = this.page(page, wrapper);
        
        // 转换为VO
        List<AiChatVO> voList = resultPage.getRecords().stream().map(chat -> {
            AiChatVO vo = new AiChatVO();
            BeanUtils.copyProperties(chat, vo);
            
            // 处理标签
            if (StringUtils.hasText(chat.getTags())) {
                vo.setTags(Arrays.asList(chat.getTags().split(",")));
            }
            
            // 处理共享用户
            if (chat.getShareType() != null && chat.getShareType() == 2 &&
                StringUtils.hasText(chat.getSharedUserIds())) {
                vo.setSharedUserIds(Arrays.asList(chat.getSharedUserIds().split(",")));
            }
            
            return vo;
        }).collect(Collectors.toList());
        
        // 创建并返回分页结果
        PageResult<AiChatVO> pageResult = new PageResult<>();
        pageResult.setRecords(voList);
        pageResult.setTotal(resultPage.getTotal());
        pageResult.setCurrent(resultPage.getCurrent());
        pageResult.setSize(resultPage.getSize());
        return pageResult;
    }
    
    @Override
    @Transactional
    @DataCacheEvict(prefix = CACHE_CHAT_LIST_PREFIX, key = "#ids")
    public Boolean batchDeleteChats(List<String> ids) {
        if (ids == null || ids.isEmpty()) {
            return false;
        }
        
        // 管理员批量删除，需要删除所有关联数据
        for (String chatId : ids) {
            // 删除对话的消息
            LambdaQueryWrapper<AiChatMessage> messageWrapper = new LambdaQueryWrapper<>();
            messageWrapper.eq(AiChatMessage::getChatId, chatId);
            aiChatMessageMapper.delete(messageWrapper);
            
            // 删除收藏
            LambdaQueryWrapper<AiChatFavorite> favoriteWrapper = new LambdaQueryWrapper<>();
            favoriteWrapper.eq(AiChatFavorite::getChatId, chatId);
            favoriteMapper.delete(favoriteWrapper);
            
            // 删除标签关联
            LambdaQueryWrapper<AiChatTagRel> tagRelWrapper = new LambdaQueryWrapper<>();
            tagRelWrapper.eq(AiChatTagRel::getChatId, chatId);
            tagRelMapper.delete(tagRelWrapper);
            
            // 删除共享设置
            LambdaQueryWrapper<AiChatShare> shareWrapper = new LambdaQueryWrapper<>();
            shareWrapper.eq(AiChatShare::getChatId, chatId);
            shareMapper.delete(shareWrapper);
        }
        
        // 批量删除对话
        return this.removeByIds(ids);
    }
    
    @Override
    public Map<String, Object> getChatStats() {
        Map<String, Object> stats = new HashMap<>();
        
        // 获取总对话数
        long totalChatCount = this.count();
        stats.put("totalChatCount", totalChatCount);
        
        // 获取今日新增对话数
        LambdaQueryWrapper<AiChat> todayWrapper = new LambdaQueryWrapper<>();
        String today = LocalDateTime.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        todayWrapper.ge(AiChat::getCreateTime, today + " 00:00:00")
                   .le(AiChat::getCreateTime, today + " 23:59:59");
        long todayChatCount = this.count(todayWrapper);
        stats.put("todayChatCount", todayChatCount);
        
        // 获取各模型类型的对话数量
        Map<Integer, Long> modelTypeCount = new HashMap<>();
        
        // OpenAI模型对话数
        LambdaQueryWrapper<AiChat> openAIWrapper = new LambdaQueryWrapper<>();
        openAIWrapper.eq(AiChat::getModelType, 1);
        modelTypeCount.put(1, this.count(openAIWrapper));
        
        // Ollama模型对话数
        LambdaQueryWrapper<AiChat> ollamaWrapper = new LambdaQueryWrapper<>();
        ollamaWrapper.eq(AiChat::getModelType, 2);
        modelTypeCount.put(2, this.count(ollamaWrapper));
        
        stats.put("modelTypeCount", modelTypeCount);
        
        // 获取消息总数
        long messageCount = aiChatMessageMapper.selectCount(new LambdaQueryWrapper<>());
        stats.put("totalMessageCount", messageCount);
        
        // 获取用户总数
        List<String> uniqueUserIds = this.baseMapper.selectUserIdList();
        stats.put("totalUserCount", uniqueUserIds.size());
        
        return stats;
    }
    
    @Override
    @DataCacheEvict(prefix = CACHE_CHAT_PREFIX, key = "#chatId")
    public Boolean updateChatStatus(String chatId, Integer status) {
        if (chatId == null || status == null) {
            return false;
        }
        
        // 获取对话
        AiChat chat = this.getById(chatId);
        if (chat == null) {
            return false;
        }
        
        // 更新状态
        chat.setStatus(status);
        return this.updateById(chat);
    }
} 